var e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e) {
  return typeof e;
} : function(e) {
  return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
};
App({
  onLaunch() {
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    var that = this;
  },
   /**
   * 验证登录
   */
  checkIsLogin() {
    if(wx.getStorageSync('user_id') != ''){
       return true;
    }
    else{
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return false;
    }
  },
  // 登录
  show_login:function(e){
    var that = this
    if (!wx.getStorageSync('userinfo')) {
      wx.login({
        success: res => {
          console.log(res.code);
          var o={
              code:res.code,
              platform:'wxapp'
            }
            wx.showModal({
              title:'提示',
              content:'获取你的昵称、头像、地区及性别',
              success(e){
                if (e.confirm) {
                  wx.getUserProfile({
                    desc: "获取你的昵称、头像、地区及性别",
                    success(ress) {
                        o.iv=ress.iv
                        o.da=ress.encryptedData
                        that.globalData.userInfo = ress.userInfo
                        console.log(that.globalData.userInfo);
                        wx.setStorageSync('userinfo', ress.userInfo);
                        that.request('/login',o,function(s){
                            that.globalData.token = s.result.token;
                            wx.setStorageSync('token', s.result.token);
                            that.request('/cars/list',{},function(e){
                              if (e.code==200) {
                                if (e.result.total>0) {
                                  that.globalData.carList = e.result
                                  wx.setStorageSync('carList', e.result);
                                }else{
                                  wx.setStorageSync('carList', "");
                                  wx.navigateTo({
                                    url: '/pages/login/login',
                                  })
                                }
                              }
                          })
                        })
                    },
                    fail(e){
                      console.log(e);
                    }
                })
                }
              }
            })
          wx.getLocation({
              success:function(res){
                  console.log(res);
                  that.globalData.loc = res
              }
          })
        }
      })
    }else{
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    // var i = getCurrentPages();
    //     if (i.length > 0) {
    //         var n = i[i.length - 1];
    //         n.selectComponent("#login").setData({
    //           hidden_login: !1
    //         });
    //     } else {
    //         if (e > 10) return;
    //         setTimeout(function() {
    //             app.show_bind_mobile(e + 1);
    //         }, 500);
    //         console.log(n.selectComponent("#login"));
    //     }
  },
  // 请求
  request: function(i, n, o, a, s, c) {
    console.log(i)
    if(i!= "/Manage/Management/login" && i!="/Manage/Management/getOpenid"){
      this.checkIsLogin();
    }
    n = "object" == (void 0 === n ? "undefined" : e(n)) && n ? n : {};
    var r, l = this;
    s = s || "POST";
    if(a){
      r=a;
    }else{
      r=this.globalData.url
    }
    var url = r + i;
    wx.request({
      url: url,
      data: n,
      method: s,
      header: l.globalData.token
            ?{"Content-Type": "application/x-www-form-urlencoded","token":l.globalData.token}
            :{"Content-Type": "application/x-www-form-urlencoded"},
      success: function(e) {
          if (e.statusCode==200) {//服务器正常情况下都返回200
            if(e.data.code==401){//接口报错401代表认证失败
              //执行更新token。，获取code
              l.updatetoken(function(res){
                l.request(i, n, o, a, s);
              });
            }
            // 失败信息提示
            if(e.data.code!=200 && e.data.code!=227){
              wx.showToast({
                title: e.data.msg,
                icon: 'none',
                duration: 2000
              })
              return false;
            }
            return "function" == typeof o && o(e.data);
          }else{
            var msg=e.data.msg?e.data.msg:'网络错误';
            wx.showToast({
              title:msg,
              icon: "none",
              duration: 3e3
          })
        }
      },
      fail: function(e) {
          wx.hideLoading({
            success: (res) => {},
          })
          return e = {
              data: {
                  msg: "网络错误:" + e.errMsg,
                  status: -1,
                  result: null
              }
          }, "function" == typeof o && o(e);
      },
      complete(e){
        return "function" == typeof c && c();
        // wx.hideNavigationBarLoading();
        // wx.stopPullDownRefresh();
      }
    });
  },  
  updatetoken:function(bk){
    var l=this
    wx.login({
      success: res => {
          var to={
              code:res.code,
              platform:'wxapp',
            }
            l.request('/login',to,function(ss){
              //设置新token
              wx.setStorageSync('token', ss.result.token);
              l.globalData.token = ss.result.token;
              //重新调用自身，传原参
              return "function" == typeof bk && bk(ss);
          })
      }
    })
  },
  getCarList(e){
    var that = this
    wx.request({
      url: this.globalData.url + '/cars/list',
      header: this.globalData.token
            ?{"Content-Type": "application/x-www-form-urlencoded","token":this.globalData.token}
            :{"Content-Type": "application/x-www-form-urlencoded"},
      success(res){
        if (res.data.code==200) {
            if (res.data.result.total>0) {
              wx.setStorageSync('carList', res.data.result);
            }else{
              console.log(that.globalData.show_login);
              that.globalData.show_login = true
              wx.setStorageSync('carList', '');
            }
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    url:'https://x.meitucc.com/api',
    iconsUrl:'https://x.meitucc.com',
    token:'',
    show_login:true,
    b_id:0,
    b_name:'',
    accountIndex:0
  },
  //获取 b_id
  get_b_id:function(){
      if(this.globalData.b_id == 0){
        this.globalData.b_id = wx.getStorageSync('user').b_id;
        return wx.getStorageSync('user').b_id
      }else{
        return this.globalData.b_id
      }
  },
  // 退出登录
  loginout(e){
    wx.removeStorageSync("user");
    wx.removeStorageSync("user_id");
    wx.removeStorageSync("role_id");
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
  /**
   * 上传图片单图
   */
  uploadFile(fileUrl,formData, callback) {
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    })
    var url=this.globalData.url+'/Manage/Management/storeImageUpload';
    wx.uploadFile({
      url: url,
      filePath: fileUrl, 
      name: 'file',
      header: { "Content-Type": "multipart/form-data" },
      formData: {
        ... formData,
      },
      success: function (res) {
        console.log(res);
        if (res.statusCode != 200) { 
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
          return;
        }
        // JSON.parse()方法是将JSON格式字符串转换为js对象
        var result = JSON.parse(res.data);
        callback && callback(result);
      },
      fail: function (e) {wx.showModal({ title: '提示',content: '上传失败',showCancel: false})},
      complete: function () {wx.hideToast();}  //隐藏Toast
    })

  },

  /**
   * 显示成功提示框(带确定按钮)
   */
  showSuccess(msg, callback) {
    wx.showModal({
      title: '成功提示',
      content: msg,
      showCancel: false,
      success(res) {
        callback && callback();
      }
    });
  },
  /**
   * 显示成功提示框(Toast版本)
   */
  showSuccessToast(msg, callback){
    wx.showToast({
      title: msg,
      icon: 'success',
      mask: true,
      duration: 2000,
      success() {
        callback && (setTimeout(() => {
          callback();
        }, 1500));
      }
    });
  },
  /**
   * 显示失败提示框
   */
  showError(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success(res) {
        // callback && (setTimeout(() => {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },
})
